using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ERP.ProductionManage;
using ERP.ProductionManage.Dtos;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace ERP.Web.Controllers
{
    public class CustomerOrderController : Controller
    {
        private readonly ICustomerOrderService _customerOrderService;
        private readonly ILogger<CustomerOrderController> _logger;

        public CustomerOrderController(
            ICustomerOrderService customerOrderService,
            ILogger<CustomerOrderController> logger)
        {
            _customerOrderService = customerOrderService;
            _logger = logger;
        }

        /// <summary>
        /// 客户订单管理页面
        /// </summary>
        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 获取客户订单列表数据
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetCustomerOrders(GetCustomerOrderInputDto input)
        {
            try
            {
                _logger.LogInformation("获取客户订单列表，参数: {@Input}", input);
                var result = await _customerOrderService.GetListAsync(input);
                
                return Json(new
                {
                    code = 0,
                    msg = "",
                    count = result.TotalCount,
                    data = result.Items
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取客户订单列表失败");
                return Json(new
                {
                    code = 500,
                    msg = ex.Message,
                    count = 0,
                    data = new List<CustomerOrderDto>()
                });
            }
        }

        /// <summary>
        /// 获取客户订单详情
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetCustomerOrder(int id)
        {
            try
            {
                _logger.LogInformation("获取客户订单详情，ID: {Id}", id);
                var result = await _customerOrderService.GetAsync(id);
                return Json(new { success = true, data = result });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取客户订单详情失败，ID: {Id}", id);
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 生成订单编码
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GenerateOrderCode()
        {
            try
            {
                var code = await _customerOrderService.GenerateOrderCodeAsync();
                _logger.LogInformation("生成订单编码: {Code}", code);
                return Json(new { success = true, code = code });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成订单编码失败");
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 创建客户订单
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> CreateCustomerOrder(CreateCustomerOrderDto input)
        {
            _logger.LogInformation("创建客户订单，参数: {@Input}", input);
            
            if (!ModelState.IsValid)
            {
                var errors = string.Join("; ", ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage));
                _logger.LogWarning("创建客户订单参数验证失败: {Errors}", errors);
                return Json(new { success = false, message = errors });
            }

            try
            {
                var result = await _customerOrderService.CreateAsync(input);
                _logger.LogInformation("创建客户订单成功，ID: {Id}", result.Id);
                return Json(new { success = true, data = result });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建客户订单失败");
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 更新客户订单
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> UpdateCustomerOrder(UpdateCustomerOrderDto input)
        {
            _logger.LogInformation("更新客户订单，参数: {@Input}", input);
            
            if (!ModelState.IsValid)
            {
                var errors = string.Join("; ", ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage));
                _logger.LogWarning("更新客户订单参数验证失败: {Errors}", errors);
                return Json(new { success = false, message = errors });
            }

            try
            {
                var result = await _customerOrderService.UpdateAsync(input.Id, input);
                _logger.LogInformation("更新客户订单成功，ID: {Id}", input.Id);
                return Json(new { success = true, data = result });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新客户订单失败，ID: {Id}", input.Id);
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 删除客户订单
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> DeleteCustomerOrder(int id)
        {
            _logger.LogInformation("删除客户订单，ID: {Id}", id);
            
            try
            {
                await _customerOrderService.DeleteAsync(id);
                _logger.LogInformation("删除客户订单成功，ID: {Id}", id);
                return Json(new { success = true });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除客户订单失败，ID: {Id}", id);
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 获取可选择的物料列表
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetMaterialsForSelect()
        {
            try
            {
                var result = await _customerOrderService.GetMaterialsForSelectAsync();
                _logger.LogInformation("获取可选择的物料列表成功，数量: {Count}", result.Count);
                return Json(new { success = true, data = result });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取可选择的物料列表失败");
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 获取订单详情列表
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetOrderDetails(int customerOrderId)
        {
            try
            {
                _logger.LogInformation("获取订单详情列表，订单ID: {CustomerOrderId}", customerOrderId);
                var result = await _customerOrderService.GetOrderDetailsAsync(customerOrderId);
                
                // 返回LayUI表格需要的格式
                return Json(new 
                { 
                    code = 0,
                    msg = "",
                    count = result.Count,
                    data = result 
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取订单详情列表失败，订单ID: {CustomerOrderId}", customerOrderId);
                return Json(new 
                { 
                    code = 500,
                    msg = ex.Message,
                    count = 0,
                    data = new List<CustomerOrderDetailDto>() 
                });
            }
        }

        /// <summary>
        /// 添加订单详情
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> CreateOrderDetail(CreateCustomerOrderDetailDto input)
        {
            _logger.LogInformation("添加订单详情，参数: {@Input}", input);
            
            if (!ModelState.IsValid)
            {
                var errors = string.Join("; ", ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage));
                _logger.LogWarning("添加订单详情参数验证失败: {Errors}", errors);
                return Json(new { success = false, message = errors });
            }

            try
            {
                var result = await _customerOrderService.CreateOrderDetailAsync(input);
                _logger.LogInformation("添加订单详情成功，ID: {Id}", result.Id);
                return Json(new { success = true, data = result });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "添加订单详情失败");
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 更新订单详情
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> UpdateOrderDetail(int detailId, UpdateCustomerOrderDetailDto input)
        {
            _logger.LogInformation("更新订单详情，ID: {Id}, 参数: {@Input}", detailId, input);
            
            if (!ModelState.IsValid)
            {
                var errors = string.Join("; ", ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage));
                _logger.LogWarning("更新订单详情参数验证失败: {Errors}", errors);
                return Json(new { success = false, message = errors });
            }

            try
            {
                var result = await _customerOrderService.UpdateOrderDetailAsync(detailId, input);
                _logger.LogInformation("更新订单详情成功，ID: {Id}", result.Id);
                return Json(new { success = true, data = result });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新订单详情失败，ID: {Id}", detailId);
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 删除订单详情
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> DeleteOrderDetail(int detailId)
        {
            _logger.LogInformation("删除订单详情，ID: {Id}", detailId);
            
            try
            {
                await _customerOrderService.DeleteOrderDetailAsync(detailId);
                _logger.LogInformation("删除订单详情成功，ID: {Id}", detailId);
                return Json(new { success = true });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除订单详情失败，ID: {Id}", detailId);
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 生成生产工单
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> GenerateProductionOrder(int customerOrderId)
        {
            _logger.LogInformation("生成生产工单，订单ID: {CustomerOrderId}", customerOrderId);
            
            try
            {
                await _customerOrderService.GenerateProductionOrderAsync(customerOrderId);
                _logger.LogInformation("生成生产工单成功，订单ID: {CustomerOrderId}", customerOrderId);
                return Json(new { success = true, message = "生产工单生成成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成生产工单失败，订单ID: {CustomerOrderId}", customerOrderId);
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 导出客户订单
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> Export(GetCustomerOrderInputDto input)
        {
            try
            {
                _logger.LogInformation("导出客户订单，参数: {@Input}", input);
                var fileBytes = await _customerOrderService.ExportAsync(input);
                var fileName = $"客户订单_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
                
                return File(fileBytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "导出客户订单失败");
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 获取产品选择列表
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetProductsForSelect(GetProductSelectInputDto input)
        {
            try
            {
                _logger.LogInformation("获取产品选择列表，参数: {@Input}", input);
                var result = await _customerOrderService.GetProductsForSelectAsync(input);
                
                return Json(new
                {
                    code = 0,
                    msg = "",
                    count = result.TotalCount,
                    data = result.Items
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取产品选择列表失败");
                return Json(new
                {
                    code = 500,
                    msg = ex.Message,
                    count = 0,
                    data = new List<ProductSelectDto>()
                });
            }
        }

        /// <summary>
        /// 获取客户选择列表
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetCustomersForSelect(GetCustomerSelectInputDto input)
        {
            try
            {
                _logger.LogInformation("获取客户选择列表，参数: {@Input}", input);
                var result = await _customerOrderService.GetCustomersForSelectAsync(input);
                
                return Json(new
                {
                    code = 0,
                    msg = "",
                    count = result.TotalCount,
                    data = result.Items
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取客户选择列表失败");
                return Json(new
                {
                    code = 500,
                    msg = ex.Message,
                    count = 0,
                    data = new List<CustomerSelectDto>()
                });
            }
        }
    }
} 